<?php
namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Session;
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * 通用上传接口
 * Class Upload
 * @package app\api\controller
 */
class FileUpload extends Controller
{
    protected function _initialize()
    {
        parent::_initialize();
        if (!Session::has('admin_id')) {
            $result = [
                'error' => 1,
                'message' => '未登录'
            ];

            return json($result);
        }
    }

    /**
     * 实例化阿里云oos
     * @return object 实例化得到的对象
     */
    function new_oss()
    {
        vendor('Alioss.autoload');
        $config = config("ALIOSS_CONFIG");
        $oss    = new OssClient($config['KEY_ID'], $config['KEY_SECRET'], $config['END_POINT']);
        return $oss;
    }

    /**
     * 上传文件到oss并删除本地文件
     * @param  string $path 文件路径
     * @return bollear      是否上传
     */
    function oss_upload($path)
    {
        $path1 = $path;
        // 获取配置项
        $bucket = config('ALIOSS_CONFIG.BUCKET');
        // 先统一去除左侧的.或者/ 再添加./
        $oss_path = ltrim($path, './');
        $path     = $oss_path;

        if (file_exists($path)) {
            // 实例化oss类
            $oss = $this->new_oss();
            // 上传到oss
            $oss1 = $oss->uploadFile($bucket, $oss_path, $path);
            // 如需上传到oss后 自动删除本地的文件 则删除下面的注释
//                dump(unlink($path));
            return $oss1;
        }
        return false;
    }


    /**
     * 通用上传接口
     * @return \think\response\Json
     */
    public function upload__(Request $request)
    {
        foreach ($_FILES as $key => $value) {
            $file_key = $key;
        }

        $config = [
            'size' => 42949672960,
            'ext' => 'jpg,jpeg,gif,png,bmp,mp3,wav,wma,mp4,avi,wmv,rm,rmvb,mpg,mpeg,3gp,mov,flv,mkv,caf'
        ];

        $res_rules = $request->file($file_key)->check($config);

        if (empty($res_rules)) {
            $result = [
                'error' => 1,
                'message' => '文件验证不通过'
            ];
            return json($result);
        }

        $object_name  = $request->file($file_key)->getInfo('name');//拿到文件名
        $explod_obect = pathinfo($object_name);//拆分
        $ali_new_name = md5($explod_obect['filename']) . '.' . $explod_obect['extension'];//加密
        $date         = date('Y-m-d', time());//时间

        try {
            // 获取配置项
            $bucket = config('ALIOSS_CONFIG.BUCKET');
            // 实例化oss类
            $oss  = $this->new_oss();
            $path = $request->file($file_key)->getRealPath();
            // 上传到oss
            $oss1 = $oss->uploadFile($bucket, 'uploads/' . $date . '/' . $file_key . '/' . $ali_new_name, $path);
            if ($oss1) {
                $url_return = $oss1['info']['url'];
                $url_return = str_replace('http://', 'https://', $url_return);
                $result = [
                    'error' => 0,
                    'type' => $file_key,
                    'url' => $url_return,
                    'file_name'=>$explod_obect['filename']
                ];

            } else {
                $result = [
                    'error' => 1,
                    'message' => $request->file($file_key)->getError()
                ];
            }
            return json($result);
        } catch (OssException $e) {
            return json(['error' => 500, 'message' => $e->getMessage()]);
        }

    }


    public function upload(Request $request)
    {
        foreach ($_FILES as $key => $value) {
            $file_key = $key;
        }
        $config = [
            'size' => 42949672960,
            'ext' => 'jpg,jpeg,gif,png,bmp,mp3,wav,wma,mp4,avi,wmv,rm,rmvb,mpg,mpeg,3gp,mov,flv,mkv,caf'
        ];

        $res_rules = $request->file($file_key)->check($config);

        if (empty($res_rules)) {
            $result = [
                'code' => 1,
                'message' => '文件验证不通过'
            ];
            return json($result);
        }

        try {
            //先上传到本地
            $info = $request->file($file_key)->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . "$file_key");
            if ($info) {
                $upload_file_path = $request->domain() . DS . 'public' . DS . 'uploads'. DS . "$file_key" . DS . $info->getSaveName();
                $upload_file_path = str_replace("\\","/",$upload_file_path);
                $result           = [
                    'error' => 0,
                    'type' => $file_key,
                    'url' => $upload_file_path,
                    'file_name'=>$info->getSaveName()
                ];
                return json($result);
            }
        } catch (Exception $exception) {

            $result           = [
                'error' => 1,
                'message' => $request->file($file_key)->getError(),

            ];
            return json($result);
        }
    }


    private function check_dir($dirname = '')
    {
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            return ['code' => 'ERROR', 'info' => '文件创建失败'];
        } else {
            if (!is_writeable($dirname)) {
                return ['code' => 'ERROR', 'info' => '文件不可写'];
            } else {
                return ['code' => 'SUCCESS', 'info' => 'SUCCESS_DIR'];
            }
        }
    }

    /**
     * 删除oss上指定文件
     * @param  string $object 文件路径 例如删除 /Public/README.md文件  传Public/README.md 即可
     */
    function oss_delet_object($object)
    {
        // 实例化oss类
        $oss = $this->new_oss();
        // 获取bucket名称
        $bucket = config('ALIOSS_CONFIG.BUCKET');
        $test   = $oss->deleteObject($bucket, $object);
    }
}